﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using System.Web.Mvc;
using CafeOnline.MvcFramework.Composition;
using CafeOnline.MvcFramework.Interfaces;

namespace CafeOnline.MvcFramework.Web {
    [Export]
    public class ImportControllerFactory : DefaultControllerFactory {
        #region Fields
#pragma warning disable 649
        [ImportMany]
        private IEnumerable<PartFactory<IController, IControllerMetadata>> ControllerFactories;
        
#pragma warning restore 649
        #endregion

        #region Methods
        /// <summary>
        /// Creates an instance of a controller for the specified name.
        /// </summary>
        /// <param name="requestContext">The current request context.</param>
        /// <param name="controllerName">The name of the controller.</param>
        /// <returns>An instance of a controller for the specified name.</returns>
        public override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName) {
            var factory = ControllerFactories
                .Where(f => f.Metadata.Name.Equals(controllerName, StringComparison.InvariantCultureIgnoreCase) ||
                    f.Metadata.Name.Equals(controllerName+"Controller", StringComparison.InvariantCultureIgnoreCase))
                .FirstOrDefault();

            if (factory != null) {
                return factory.CreatePart();
            }
            
            return base.CreateController(requestContext, controllerName);
        }
        #endregion
    }
    [Export]
    public class ImportWebApiControllerFactory : IHttpControllerActivator {
        [ImportMany]
        private IEnumerable<PartFactory<IHttpController, IControllerMetadata>> WebApiControllerFactories;

        public IHttpController Create(System.Net.Http.HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) {
            var controllerName = controllerType.Name;
            var webApiFactory = WebApiControllerFactories.Where(f => f.Metadata.Name.Equals(controllerName, StringComparison.InvariantCultureIgnoreCase) ||
                    f.Metadata.Name.Equals(controllerName + "Controller", StringComparison.InvariantCultureIgnoreCase))
                .FirstOrDefault();
            if (webApiFactory != null) {
                return webApiFactory.CreatePart();
            }
            return null;
        }
    }
}
